package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    @Scheduled(cron = "0 * * * * ?") //每分钟执行一次
    //@Scheduled(cron = "0/5 * * * * ? ")
    public void processTimeOuterOrder(){
        //查询出状态为待支付的订单并且下单时间 < 当前时间 - 15min
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> list = orderMapper.selectStatusAndOrderTime(Orders.PENDING_PAYMENT, time);
        if (list != null && !list.isEmpty()) {
            for (Orders orders : list) {
                //把状态修改为已取消
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("订单超时,已取消");
                orders.setStatus(Orders.CANCELLED);
                orderMapper.update(orders);
            }
        }
    }

    @Scheduled(cron = "0 0 1 * * ?")
    //@Scheduled(cron = "1/5 * * * * ? ")
    public void processDELIVERY_IN_PROGRESSOrder() {
        //查询出状态为派送中的订单并且下单时间为上一天的订单
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> list = orderMapper.selectStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, time);
        if (list != null && !list.isEmpty()) {
            for (Orders orders : list) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
